package com.polaris.live.ui.party.activity

import android.content.Intent
import android.os.Build
import android.os.Bundle
import com.gyf.immersionbar.ImmersionBar
import com.polaris.live.adapter.party.SpectatorFragmentAdapter
import com.polaris.live.common.network.AppException
import com.polaris.live.common.util.DebounceHelper
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.LiveConst
import com.polaris.live.databinding.ActivityPartySpectatorBinding
import com.polaris.live.floating.FloatingWindowManager
import com.polaris.live.im.sfs.bean.live.SendLiveCloseMessage
import com.polaris.live.im.sfs.core.SmartFoxManager
import com.polaris.live.manager.LiveStateManager
import com.polaris.live.resp.back_resp.DisplayUserBean
import com.polaris.live.resp.event.PartyExitEvent
import com.polaris.live.resp.event.WebSpectatorEvent
import com.polaris.live.translation.R.string.sure_exit_party_tips
import com.polaris.live.ui.game.GameUtils
import com.polaris.live.ui.live.bean.LiveInitInfo
import com.polaris.live.ui.party.PartyUserStateUtil
import com.polaris.live.ui.party.activity.base.BasePartySpectatorActivity
import com.polaris.live.ui.party.fragment.base.BasePartySpectatorFragment
import com.polaris.live.ui.party.utils.RoomControlProxy
import com.polaris.live.utils.XActivityUtils
import com.polaris.live.utils.getIntOrString
import com.polaris.live.utils.getLongOrString
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.utils.route.RouterUtils
import com.polaris.live.viewmodel.party.PartySpectatorModel
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * PartyAnchorActivity 语聊房用户端
 * @author Created by 天晴 on 2024/2/24 11:13
 * @since 1.0.0
 **/
class PartySpectatorActivity : BasePartySpectatorActivity<PartySpectatorModel, ActivityPartySpectatorBinding>() {

    private val mAdapter by lazy {
        SpectatorFragmentAdapter(supportFragmentManager, lifecycle)
    }
    private var mLiveExiting: Boolean = false
    private var mShowTips = false
    private var mPartyClose = false //直播间是否已关闭
    private var mCloseMessage: SendLiveCloseMessage? = null //在游戏时保存直播间关闭信息

    //h5转跳后如果 主播id与路由的主播id不同先切换房间 然后存储的子路由
    private var mH5ChildRouter: String? = null
    private var minimize = false  //是否最小化

    /**
     * 房间控制
     */
    private val mRoomControl by lazy {
        RoomControlProxy(
            LiveConst.RequestLiveType.PARTY,
            mViewModel,
            this,
            mBinding.vEdit,
            mBinding.viewpager2,
            mAdapter,
            this,
            this,
        )
    }

    override fun initImmersionBar() {
        ImmersionBar.with(this)
            .transparentBar()
            .transparentNavigationBar()
            .init()
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        XActivityUtils.killOtherRoomActivity(PartySpectatorActivity::class.java)
        val mAnchorId = intent.getLongOrString(LiveConst.Params.ANCHORID, -1L)

        val mLiveType = intent.getIntOrString(LiveConst.Params.LIVETYPE, LiveConst.Type.PARTY_LIVE)


        val info = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getParcelableExtra(LiveConst.Params.LIVEINITINFO, LiveInitInfo::class.java)
        } else {
            intent.getParcelableExtra(LiveConst.Params.LIVEINITINFO)
        }
        val mRoomId = intent.getStringExtra(LiveConst.Params.ROOMID)
        if (mAnchorId <= 0) {
            finish()
            return
        }
        //观众进入直播状态
        LiveStateManager.updateSpectateState(true)

        mBinding.viewpager2.adapter = mAdapter
        mBinding.viewpager2.offscreenPageLimit = 1
        initListener()
        openOneRoom(mAnchorId, info, mLiveType, mRoomId)

        showMusicWindowView()

    }

    /**
     * 进入第一个房间
     */
    private fun openOneRoom(mAnchorId: Long, liveInitInfo: LiveInitInfo?, mLiveType: Int, mRoomId: String?) {
        mRoomControl.startRoomControl(mAnchorId, mLiveType, liveInitInfo = liveInitInfo, roomId = mRoomId)
        if (liveInitInfo != null) { //有这个代表没有之前连接的  检查一下房间有没有加入成功
            val lastRoom = SmartFoxManager.getLiveRoom()
            //如果上次是断开连接，这次连接上了，需要重连
            if (lastRoom == null) {
                mRoomControl.network(true, SmartFoxManager.isLiveConnected())
            }
        }
    }

    private fun initListener() {
        mBinding.gestuer.setOnListener({
            getFragment()?.onSwipeLeft()
        }, {
            getFragment()?.onSwipeRight()
        }, {
            if (mShowTips) {
                ToastGravity.showGravity(sure_exit_party_tips)
            }

        }, {
            if (mShowTips) {
                ToastGravity.showGravity(sure_exit_party_tips)
            }

        })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: PartyExitEvent) {
        if (event.isExit) {
            GameUtils.dismissGameFragment(this)
            mRoomControl.exitCurrentRoom()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEndSpectatorEvent(event: WebSpectatorEvent) {
        if (event.isNeedClose) {
            mRoomControl.closeActivity()
        } else {
            getFragment()?.switchUserRoom(event.anchorId, event.childRouter)
            if (event.anchorId != getFragment()?.mAnchorId) {
                mH5ChildRouter = event.childRouter
            }
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        intent?.let {
            val mAnchorId = intent.getLongOrString(LiveConst.Params.ANCHORID, -1L)
            val mLiveType = intent.getIntOrString(LiveConst.Params.LIVETYPE, LiveConst.Type.PARTY_LIVE)
            val mRoomId = intent.getStringExtra(LiveConst.Params.ROOMID)
            if (mAnchorId > 0) {
                mRoomControl.switchRoom(mAnchorId, mLiveType, mRoomId)
            }
        }
    }

    /**
     * 界面onResume
     */
    override fun onResume() {
        super.onResume()
        mRoomControl.onResume()
    }

    /**
     * 界面onPause
     */
    override fun onPause() {
        super.onPause()
        mRoomControl.onPause()
    }

    override fun onDestroy() {
        mRoomControl.onDestroy()
        super.onDestroy()
        if (!FloatingWindowManager.isMinimize()) {
            //观众进入直播状态
            LiveStateManager.updateSpectateState(false)
            PartyUserStateUtil.inTheMaiSeat = false
            PartyUserStateUtil.siteMicStatus = null
        }
    }

    private fun getFragment(): BasePartySpectatorFragment<*, *>? {
        return mRoomControl.getCurrentBean()?.fragment
    }

    override fun onNetwork(isNetwork: Boolean, isConnected: Boolean) {
        mRoomControl.network(isNetwork, isConnected)
    }

    override fun onBackPressed() {
        if (mLiveExiting) {
            return
        }
        if (getFragment()?.onBackPressed() == false) {
            mRoomControl.closeActivity()
            super.onBackPressed()
        }
    }

    private fun exitActivity(closeMEssage: SendLiveCloseMessage? = null) {
        if (mLiveExiting) {
            return
        }
        mLiveExiting = true
        mRoomControl.closeActivity()
        if (!GameUtils.gameRun) {
            toEndActivity(closeMEssage)
        } else {
            mCloseMessage = closeMEssage
        }
    }

    private fun toEndActivity(closeMEssage: SendLiveCloseMessage? = null) {
        closeMEssage?.let {
            Router.builder(RoutePath.LIVE_SPECTATOR_END_ACTIVITY)
                .withAny("data", it)
                .withInt("fromType", LiveConst.Type.PARTY_LIVE)
                .navigation(this)
        }

    }

    /**
     *===================== fragment的回调========================
     */

    override fun closeActivity(closeMessage: SendLiveCloseMessage?) {
        if (minimize) {
            finish()
        } else {
            exitActivity(closeMessage)
        }


    }

    override fun nextData(displayUserBean: DisplayUserBean) {
        DebounceHelper.singleClick(1000) { //防止多次点击
            mRoomControl.nextData(displayUserBean)
        }
    }

    override fun prohibitSliding(sliding: Boolean, showTips: Boolean) {
        this.mShowTips = showTips
        mBinding.viewpager2.isUserInputEnabled = !sliding
        mBinding.gestuer.setTouch(sliding)

    }

    override fun enterRoomPassword(pws: String) {
        mRoomControl.enterRoom(pws)
    }

    override fun onBannerTouch(openTouch: Boolean) {
        mBinding.gestuer.setOpenTouch(openTouch)
    }

    override fun onMinimize(minimize: Boolean) {
        this.minimize = minimize
    }

    /**
     * ============RoomControlProxy的回调=====================
     */
    override fun joinSuccess(liveInitInfo: LiveInitInfo) {
        RouterUtils.routerGotoChild(this, mBinding.root)
        val route = mH5ChildRouter
        if (route != null) {
            RouterUtils.routerGoto(route)
            mH5ChildRouter = null
        }
    }

    override fun joinError(appException: AppException) {
    }

    override fun exitLastSuccess() {
    }

    override fun exitSuccess() {
        if (!GameUtils.gameRun) {
            finish()
        } else {
            mPartyClose = true
        }

    }

    /**
     * ===============游戏监控回调========================
     */
    override fun gameStart() {
    }

    override fun gameClose() {
        if (mPartyClose) {
            toEndActivity(mCloseMessage)
            finish()
        }
    }
}